package com.jctrip.hotel.common.util;

import com.tinify.Options;
import com.tinify.Source;
import com.tinify.Tinify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: zxy
 * @CreateTime: 2023-10-24 21:34
 * @Description:
 */
@Component
@Slf4j
public class PictureUtil implements InitializingBean {
    private static String apiKey;

    @Value("${feign.url.tiny-png}")
    private String APIKEY;

    public static byte[] resizedPic(String url, Integer width, Integer height) throws IOException {
        Tinify.setKey(apiKey);
        Source source = Tinify.fromUrl(url);
        Options options = new Options()
                .with("method", "thumb")
                .with("width", width)
                .with("height", height);
        Source resized = source.resize(options);
        return resized.toBuffer();
    }

    public static String resizedPicAndUpload(String url, String fileName) throws IOException {
        Tinify.setKey(apiKey);
        Source source = Tinify.fromUrl(url);
        return OssUtil.updaload(source.toBuffer(), fileName);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        apiKey = APIKEY;
    }
}
